<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\http\HttpRequest;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;

/**
 * app action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class AppAction extends CommonAction {

    protected $serviceBean = 'app.app.service';
    protected $actionTitle = '应用';

    //数据列表页面
    public function index( HttpRequest $request ) {
        parent::index($request);
        $this->setView('app/app_index');
        $this->assign("title", $this->actionTitle."列表");
        $this->assign('breadcrumb', array('MPE管理',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
    }

    //数据添加页面
    public function add(HttpRequest $request) {
        throw new UnSupportedOperationException();
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $item = $service->getItem($id);
        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        $data['secret_key'] = StringUtils::genGlobalUid(true, 32); //生成密钥
        parent::__insert($data);
    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        parent::__update($data, $id);

    }

    public function delete(HttpRequest $request)
    {
        $id = $request->getParameter('id', 'trim');
        //如果已经被安装了则不可以删除
        $mpeService = Beans::get('app.mpe.service');
        if ( $mpeService->count(array('appid' => $id)) > 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '该应用已经被客户安装了，不允许删除');
        }
        parent::delete($request); // TODO: Change the autogenerated stub
    }
}
